package cn.takujo.takujoframework.common.util.code_generator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

public class JavaTemplate {

	private static TemplateEngine engine;

	static {
		ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
		resolver.setPrefix("templates/java/");
		resolver.setSuffix(".java");
		resolver.setCharacterEncoding("UTF-8");
		resolver.setTemplateMode("TEXT");
		engine = new TemplateEngine();
		engine.setTemplateResolver(resolver);
	}

	/**
	 * 根据java模板生成java文件
	 * 
	 * @param variables
	 *            注入的参数集
	 * @param javaTemplate
	 *            java模板代码（例：bean/Bean，不应带.java后缀）
	 * @param outPath
	 *            输出的文件路径，不应带.java后缀
	 * @throws IOException
	 *             异常
	 */
	public static void process(Map<String, Object> variables, String javaTemplate, String outPath) throws IOException {
		Context context = new Context();
		if (variables != null) {
			context.setVariables(variables);
		}
		if (javaTemplate != null && outPath != null) {
			String base = "src/main/resources/code/java";
			String ff = base + "/" + outPath + ".java";
			File parentFile = new File(ff).getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			FileWriter write = new FileWriter(ff);
			engine.process(javaTemplate, context, write);
		}
	}

}
